<?php

declare(strict_types=1);

namespace app\middleware;

use app\Model\User;

class ApiAuthMiddleware
{
    /**
     * 处理请求
     *
     * @param Request $request
     * @param \Closure $next
     * @return Response
     */
    public function handle($request, \Closure $next)
    {
        $token = explode(' ',$request->header('authorization'));

        if(isset($token[1])){
            //判断token是否过期
            $userModel = new User();
            $userInfo = $userModel->getToken($token[1]);

            if(empty($userInfo)){
                abort(401,'Unauthorized');
            }

            if($userInfo['token_expire_time'] <= time()){
                abort(40316,'token已过期');
            }

        }else{
            abort(401,'未认证');
        }

        return $next($request);
    }
}
